<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"></el-alert>
      <el-steps :space="200" :active="parseInt(active)" finish-status="success" class="steps" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px" label-position="top">
        <el-tabs v-model="active" :tab-position="tabPosition" :before-leave="selectCats" @tab-click="changeTab">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in cateManyData" :label="item.attr_name" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(subItem,i) in item.attr_vals" :label="subItem" :key="i" border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in cateOnlyData" :label="item.attr_name" :key="item.attr_id">
              <el-input type="text" v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"/>
            <el-button type="primary" @click="addGoods" class="btnAdd">提交</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
      :visible.sync="picDialogVisible"
      width="30%">
      <img :src="picPath" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'Add',
  data () {
    return {
      tabPosition: 'left',
      active: '0',
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_number: null,
        goods_weight: null,
        goods_cat: [],
        attrs: [],
        pics: [],
        goods_introduce: ''
      },
      cateList: [],
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        attrs: []
      },
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ],
        goods_cat: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ]
      },
      cateOnlyData: [],
      cateManyData: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headers: {
        Authorization: sessionStorage.getItem('token')
      },
      picDialogVisible: false,
      picPath: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      // console.log(this.cateList)
    },
    handleChange (value) {
      this.addForm.goods_cat = value
    },
    selectCats () {
      if (this.addForm.goods_cat.length !== 3) {
        this.active = '0'
        return false
      }
    },
    async changeTab () {
      if (this.active === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length !== 0 ? item.attr_vals.split(' ') : []
        })
        this.cateManyData = res.data
        // console.log(res.data)
      }
      if (this.active === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        this.cateOnlyData = res.data
        // console.log(res.data)
      }
    },
    handleSuccess (response) {
      this.addForm.pics.push({ pic: response.data.tmp_path })
      console.log(this.addForm.pics)
    },
    handlePreview (file) {
      // console.log(file)
      this.picPath = file.response.data.url
      this.picDialogVisible = true
    },
    handleRemove (file) {
      const index = this.addForm.pics.findIndex(item => item.pic === file.response.data.tmp_path)
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },
    addGoods () {
      this.$refs.addFormRef.validate(async vaild => {
        if (!vaild) return this.$message.error('请完善商品内容')
        this.cateManyData.forEach(item => {
          this.addForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join('')
          })
        })
        this.cateOnlyData.forEach(item => {
          this.addForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
      } else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.steps {
  margin: 15px;
}

.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.btnAdd {
  margin-top: 10px;
}
</style>
